{% extends "pc/template.html" %}

{% block title %}
    订单列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
    .card {
        margin: 1rem 0;
    }
    .table-responsive {
        margin: 0;
    }
    .action-buttons .btn {
        padding: 0.25rem 0.5rem;
        margin: 0 0.2rem;
    }
    .status-badge {
        padding: 0.35em 0.65em;
        font-size: 0.75em;
        font-weight: 700;
        border-radius: 0.25rem;
    }
    .status-pending {
        background-color: #fff3cd;
        color: #856404;
    }
    .status-paid {
        background-color: #e8fff3;
        color: #28c76f;
    }
    .status-cancelled {
        background-color: #ffe4e4;
        color: #ea5455;
    }
    .status-refunded {
        background-color: #e4e4ff;
        color: #5e50ee;
    }
    .description-text {
        display: inline-block;
        max-width: 200px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: help;
        vertical-align: middle;
    }
    .product-option {
        display: flex;
        align-items: center;
        padding: 8px;
        gap: 10px;
    }
    .product-image {
        width: 40px;
        height: 40px;
        object-fit: cover;
        border-radius: 4px;
    }
    .product-info {
        flex: 1;
        min-width: 0;
    }
    .product-name {
        font-weight: 500;
        margin-bottom: 2px;
    }
    .product-details {
        font-size: 0.85em;
        color: #666;
    }
    #orderProduct {
        height: auto;
        max-height: 300px;
    }
    #orderProduct option {
        padding: 8px;
        white-space: normal;
    }
    /* 确保 Swal 弹窗显示在最上层 */
    .swal2-container {
        z-index: 9999 !important;
    }
    .swal2-popup {
        z-index: 10000 !important;
    }
    /* 确保模态框的 z-index 低于 Swal */
    .modal {
        z-index: 1050;
    }
    .modal-backdrop {
        z-index: 1040;
    }
    /* 分页样式 */
    .pagination {
        margin: 1rem 0 0 0;
        justify-content: center;
    }
    .pagination .page-link {
        padding: 0.5rem 0.75rem;
        color: #566a7f;
        background-color: #fff;
        border: 1px solid #d9dee3;
    }
    .pagination .page-item.active .page-link {
        background-color: #696cff;
        border-color: #696cff;
    }
    .pagination .page-link:hover {
        color: #696cff;
        background-color: #f5f5f9;
        border-color: #d9dee3;
    }
    .pagination .page-item.disabled .page-link {
        color: #a3a4cc;
        pointer-events: none;
        background-color: #fff;
        border-color: #d9dee3;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 订单列表卡片 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">订单列表</h5>
            <div>
                <button type="button" class="btn btn-primary" onclick="showAddOrderModal()">
                    <i class="bx bx-plus"></i> 添加订单
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>订单ID</th>
                            <th>状态</th>
                            <th>支付方式</th>
                            <th>总价</th>
                            <th>创建者</th>
                            <th>备注</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="orderTableBody">
                        <!-- 订单数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 添加订单模态框 -->
    <div class="modal fade" id="addOrderModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加订单</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addOrderForm">
                        <div class="mb-3">
                            <label class="form-label" for="orderId">订单ID <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="orderId" name="order_id" required 
                                    pattern="^[a-zA-Z0-9_-]+$" 
                                    maxlength="30"
                                    title="订单ID只能包含英文、数字、下划线和-，且长度不超过30个字符"
                                    placeholder="请输入订单ID或点击生成">
                                <button class="btn btn-outline-secondary" type="button" onclick="generateOrderId()">
                                    <i class="bx bx-refresh"></i> 生成
                                </button>
                            </div>
                            <small class="text-muted">订单ID只能包含英文、数字、下划线和-，长度不超过30个字符</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="orderPayMethod">支付方式 <span class="text-danger">*</span></label>
                            <select class="form-select" id="orderPayMethod" name="pay_method" required>
                                <option value="">请选择支付方式</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="orderProduct">购买商品 <span class="text-danger">*</span></label>
                            <div class="input-group mb-2">
                                <input type="text" class="form-control" id="productSearch" placeholder="搜索商品名称、ID或分类...">
                                <button class="btn btn-outline-secondary" type="button" onclick="clearProductSearch()">
                                    <i class="bx bx-x"></i>
                                </button>
                            </div>
                            <select class="form-select" id="orderProduct" name="buy_goodsProduct" required size="8">
                                <option value="">请选择商品</option>
                            </select>
                            <small class="text-muted">显示: 商品名称 (ID) - 分类 - 价格 - 库存</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="orderProductNumber">购买数量 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="orderProductNumber" name="buy_goodsProduct_number" 
                                min="1" required onchange="updateTotalPrice()">
                            <small class="text-muted">请输入购买数量，不能超过商品库存</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="orderStatus">状态</label>
                            <select class="form-select" id="orderStatus" name="status">
                                <option value="1">待支付</option>
                                <option value="2">已支付</option>
                                <option value="3">已取消</option>
                                <option value="4">已退款</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="orderTotalPrice">总价 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="orderTotalPrice" name="total_price" step="0.01" min="0.01" required>
                            <small class="text-muted">订单总价必须大于0</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="orderCreateUser">创建者 <span class="text-danger">*</span></label>
                            <select class="form-select" id="orderCreateUser" name="create_user" required>
                                <option value="">请选择创建者</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="orderRemark">备注</label>
                            <textarea class="form-control" id="orderRemark" name="remark" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addOrder()">添加</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    // 全局变量
    let allOrders = []; // 存储所有订单数据
    let currentPage = 1; // 当前页码
    const itemsPerPage = 10; // 每页显示的数量

    // 页面加载完成后获取订单列表、支付方式列表和用户列表
    document.addEventListener('DOMContentLoaded', function() {
        // 先获取支付方式、用户列表和商品列表，再获取订单列表
        Promise.all([
            getPayMethodList(),
            getUserList(),
            getProductList()
        ]).then(() => {
            getOrderList();
        });
    });

    // 获取支付方式列表
    function getPayMethodList() {
        return new Promise((resolve, reject) => {
            axios.get('/api/order/get_pay_method_list/')
                .then(function(response) {
                    if (response.data.code === 200) {
                        window.payMethods = response.data.data;
                        updatePayMethodOptions(response.data.data);
                        resolve(response.data.data);
                    } else {
                        reject(response.data.msg);
                    }
                })
                .catch(function(error) {
                    reject(error);
                });
        });
    }

    // 获取用户列表
    function getUserList() {
        return new Promise((resolve, reject) => {
            axios.get('/api/users/get_user_list/')
                .then(function(response) {
                    if (response.data.code === 200) {
                        window.users = response.data.data;
                        updateUserOptions(response.data.data);
                        resolve(response.data.data);
                    } else {
                        reject(response.data.msg);
                    }
                })
                .catch(function(error) {
                    reject(error);
                });
        });
    }

    // 获取商品列表
    function getProductList() {
        return new Promise((resolve, reject) => {
            axios.get('/api/product/get_product_list/')
                .then(function(response) {
                    if (response.data.code === 200) {
                        window.products = response.data.data;
                        updateProductOptions(response.data.data);
                        resolve(response.data.data);
                    } else {
                        reject(response.data.msg);
                    }
                })
                .catch(function(error) {
                    reject(error);
                });
        });
    }

    // 获取支付方式名称
    function getPayMethodName(payMethodId) {
        const payMethod = window.payMethods.find(pm => pm.id === payMethodId);
        return payMethod ? payMethod.name : '-';
    }

    // 获取用户名称
    function getUserName(userId) {
        const user = window.users.find(u => u.id === userId);
        return user ? user.username : '-';
    }

    // 更新支付方式选项
    function updatePayMethodOptions(payMethods) {
        const payMethodSelects = [
            document.getElementById('orderPayMethod')
        ];

        const options = payMethods.map(payMethod => 
            `<option value="${payMethod.id}">${payMethod.name}</option>`
        ).join('');

        payMethodSelects.forEach(select => {
            if (select) {
                select.innerHTML = '<option value="">请选择支付方式</option>' + options;
            }
        });
    }

    // 更新用户选项
    function updateUserOptions(users) {
        const userSelect = document.getElementById('orderCreateUser');

        const options = users.map(user => 
            `<option value="${user.id}">${user.username}</option>`
        ).join('');

        userSelect.innerHTML = '<option value="">请选择创建者</option>' + options;
    }

    // 更新商品选项
    function updateProductOptions(products) {
        const productSelect = document.getElementById('orderProduct');
        if (!productSelect) return;

        const options = products.map(product => {
            // 获取第一张图片的URL
            const imageUrl = product.images && product.images.length > 0 
                ? product.images[0].image  // 从图片对象中获取image字段
                : '';
            
            return `
                <option value="${product.id}" 
                    data-name="${product.name}"
                    data-id="${product.product_id}"
                    data-category="${product.category_name || '-'}"
                    data-price="${product.price}"
                    data-stock="${product.stock}"
                    data-image="${imageUrl}">
                    ${product.name} (${product.product_id}) - ${product.category_name || '-'} - ￥${product.price} - 库存: ${product.stock}
                </option>
            `;
        }).join('');

        productSelect.innerHTML = '<option value="">请选择商品</option>' + options;
        setupProductSearch();
    }

    // 设置商品搜索功能
    function setupProductSearch() {
        const searchInput = document.getElementById('productSearch');
        const productSelect = document.getElementById('orderProduct');
        
        searchInput.addEventListener('input', function() {
            const searchText = this.value.toLowerCase();
            const options = productSelect.options;
            
            for (let i = 1; i < options.length; i++) { // 跳过第一个空选项
                const option = options[i];
                const text = option.text.toLowerCase();
                const shouldShow = text.includes(searchText);
                option.style.display = shouldShow ? '' : 'none';
            }
        });
    }

    // 清除搜索
    function clearProductSearch() {
        const searchInput = document.getElementById('productSearch');
        const productSelect = document.getElementById('orderProduct');
        
        searchInput.value = '';
        const options = productSelect.options;
        for (let i = 1; i < options.length; i++) {
            options[i].style.display = '';
        }
    }

    // 自定义下拉框样式
    document.addEventListener('DOMContentLoaded', function() {
        const productSelect = document.getElementById('orderProduct');
        if (productSelect) {
            // 创建图片预览容器
            const previewContainer = document.createElement('div');
            previewContainer.id = 'productImagePreview';
            previewContainer.style.cssText = `
                position: fixed;
                display: none;
                background: white;
                padding: 12px;
                border-radius: 12px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.15);
                z-index: 9999;
                max-width: 240px;
                transition: opacity 0.2s ease-in-out;
                opacity: 0;
                border: 1px solid rgba(0,0,0,0.1);
            `;
            document.body.appendChild(previewContainer);

            // 创建加载状态指示器
            const loadingIndicator = document.createElement('div');
            loadingIndicator.style.cssText = `
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 30px;
                height: 30px;
                border: 3px solid #f3f3f3;
                border-top: 3px solid #ff7e2d;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                display: none;
            `;
            previewContainer.appendChild(loadingIndicator);

            // 添加加载动画样式
            const style = document.createElement('style');
            style.textContent = `
                @keyframes spin {
                    0% { transform: translate(-50%, -50%) rotate(0deg); }
                    100% { transform: translate(-50%, -50%) rotate(360deg); }
                }
                @keyframes fadeIn {
                    from { opacity: 0; transform: scale(0.95); }
                    to { opacity: 1; transform: scale(1); }
                }
                .preview-image {
                    width: 100%;
                    height: auto;
                    border-radius: 8px;
                    transition: transform 0.2s ease;
                }
                .preview-image:hover {
                    transform: scale(1.02);
                }
                .preview-error {
                    color: #666;
                    text-align: center;
                    padding: 20px;
                    font-size: 14px;
                }
            `;
            document.head.appendChild(style);

            let previewTimeout;
            let currentImageUrl = '';

            // 鼠标悬停时显示图片预览
            productSelect.addEventListener('mouseover', function(e) {
                const option = e.target;
                if (option.tagName === 'OPTION' && option.value) {
                    const imageUrl = option.getAttribute('data-image');
                    if (imageUrl && imageUrl !== currentImageUrl) {
                        currentImageUrl = imageUrl;
                        
                        // 清除之前的定时器
                        clearTimeout(previewTimeout);
                        
                        // 显示加载状态
                        loadingIndicator.style.display = 'block';
                        previewContainer.style.display = 'block';
                        previewContainer.style.opacity = '0';
                        
                        // 计算预览框位置
                        const rect = option.getBoundingClientRect();
                        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                        const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
                        
                        // 确保预览框不会超出视窗
                        const previewWidth = 240;
                        const previewHeight = 240;
                        const rightEdge = rect.right + previewWidth + 20;
                        const bottomEdge = rect.bottom + previewHeight + 20;
                        
                        let left = rect.right + 20;
                        let top = rect.top;
                        
                        // 如果预览框会超出右边界，则显示在左侧
                        if (rightEdge > window.innerWidth) {
                            left = rect.left - previewWidth - 20;
                        }
                        
                        // 如果预览框会超出下边界，则向上偏移
                        if (bottomEdge > window.innerHeight) {
                            top = Math.max(20, window.innerHeight - previewHeight - 20);
                        }
                        
                        previewContainer.style.left = (left + scrollLeft) + 'px';
                        previewContainer.style.top = (top + scrollTop) + 'px';
                        
                        // 加载图片
                        const img = new Image();
                        img.onload = function() {
                            loadingIndicator.style.display = 'none';
                            previewContainer.innerHTML = `
                                <img src="${imageUrl}" class="preview-image" alt="商品图片">
                            `;
                            previewContainer.style.opacity = '1';
                        };
                        img.onerror = function() {
                            loadingIndicator.style.display = 'none';
                            previewContainer.innerHTML = `
                                <div class="preview-error">
                                    <i class="bx bx-image-alt" style="font-size: 24px; color: #ccc;"></i>
                                    <p style="margin-top: 8px;">图片加载失败</p>
                                </div>
                            `;
                            previewContainer.style.opacity = '1';
                        };
                        img.src = imageUrl;
                    }
                }
            });

            // 鼠标离开时隐藏预览
            productSelect.addEventListener('mouseout', function(e) {
                if (!e.relatedTarget || !e.relatedTarget.closest('#productImagePreview')) {
                    previewTimeout = setTimeout(() => {
                        previewContainer.style.opacity = '0';
                        setTimeout(() => {
                            previewContainer.style.display = 'none';
                            currentImageUrl = '';
                        }, 200);
                    }, 100);
                }
            });

            // 预览框的鼠标事件
            previewContainer.addEventListener('mouseover', function() {
                clearTimeout(previewTimeout);
                this.style.opacity = '1';
            });

            previewContainer.addEventListener('mouseout', function() {
                previewTimeout = setTimeout(() => {
                    this.style.opacity = '0';
                    setTimeout(() => {
                        this.style.display = 'none';
                        currentImageUrl = '';
                    }, 200);
                }, 100);
            });
        }
    });

    // 获取订单列表
    function getOrderList() {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get('/api/order/get_order_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    allOrders = response.data.data;
                    currentPage = 1; // 重置到第一页
                    renderOrderTable();
                    renderPagination();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取订单列表失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 渲染订单表格
    function renderOrderTable() {
        const tbody = document.getElementById('orderTableBody');
        tbody.innerHTML = '';

        // 计算当前页的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentPageOrders = allOrders.slice(startIndex, endIndex);

        currentPageOrders.forEach(order => {
            const tr = document.createElement('tr');
            tr.setAttribute('data-id', order.id);
            tr.setAttribute('data-pay-method', order.pay_method);
            tr.setAttribute('data-create-user', order.create_user);
            tr.innerHTML = `
                <td>${order.order_id || '-'}</td>
                <td>
                    <span class="status-badge ${getStatusClass(order.status)}">
                        ${getStatusText(order.status)}
                    </span>
                </td>
                <td>${getPayMethodName(order.pay_method)}</td>
                <td>￥${order.total_price}</td>
                <td>${getUserName(order.create_user)}</td>
                <td>
                    <div class="description-text" title="${order.remark || '-'}">
                        ${order.remark || '-'}
                    </div>
                </td>
                <td>${order.create_time}</td>
                <td class="action-buttons">
                    <button class="btn btn-sm btn-danger" onclick="deleteOrder(${order.id})">
                        <i class="bx bx-trash"></i>
                    </button>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    // 渲染分页控件
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        const totalPages = Math.ceil(allOrders.length / itemsPerPage);
        
        let paginationHTML = '';
        
        // 上一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage - 1})" aria-label="Previous">
                    <i class="bx bx-chevron-left"></i>
                </a>
            </li>
        `;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            paginationHTML += `
                <li class="page-item ${currentPage === i ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        }

        // 下一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage + 1})" aria-label="Next">
                    <i class="bx bx-chevron-right"></i>
                </a>
            </li>
        `;

        pagination.innerHTML = paginationHTML;
    }

    // 切换页码
    function changePage(page) {
        if (page < 1 || page > Math.ceil(allOrders.length / itemsPerPage)) {
            return;
        }
        currentPage = page;
        renderOrderTable();
        renderPagination();
    }

    // 获取状态样式类
    function getStatusClass(status) {
        switch (parseInt(status)) {
            case 1: return 'status-pending';
            case 2: return 'status-paid';
            case 3: return 'status-cancelled';
            case 4: return 'status-refunded';
            default: return '';
        }
    }

    // 获取状态文本
    function getStatusText(status) {
        switch (parseInt(status)) {
            case 1: return '待支付';
            case 2: return '已支付';
            case 3: return '已取消';
            case 4: return '已退款';
            default: return '未知';
        }
    }

    // 生成订单ID
    function generateOrderId() {
        // 生成一个较短的UUID（只使用前8个字符）
        const timestamp = Date.now().toString(36); // 使用时间戳的36进制表示
        const randomStr = Math.random().toString(36).substring(2, 8); // 随机字符串
        const orderId = `${timestamp}-${randomStr}`.toLowerCase();
        
        // 确保不超过30个字符
        const finalOrderId = orderId.substring(0, 30);
        
        // 设置到输入框
        document.getElementById('orderId').value = finalOrderId;
    }

    // 更新总价
    function updateTotalPrice() {
        const productSelect = document.getElementById('orderProduct');
        const numberInput = document.getElementById('orderProductNumber');
        const totalPriceInput = document.getElementById('orderTotalPrice');
        
        if (productSelect.value && numberInput.value) {
            const selectedOption = productSelect.options[productSelect.selectedIndex];
            const price = parseFloat(selectedOption.getAttribute('data-price'));
            const stock = parseInt(selectedOption.getAttribute('data-stock'));
            const number = parseInt(numberInput.value);
            
            // 验证数量不超过库存
            if (number > stock) {
                Swal.fire('错误', '购买数量不能超过商品库存', 'error');
                numberInput.value = stock;
                return;
            }
            
            // 计算总价
            const totalPrice = price * number;
            totalPriceInput.value = totalPrice.toFixed(2);
        }
    }

    // 添加订单
    function addOrder() {
        const form = document.getElementById('addOrderForm');
        const formData = new FormData(form);
        
        // 验证必填字段
        const orderId = formData.get('order_id');
        const payMethod = formData.get('pay_method');
        const totalPrice = formData.get('total_price');
        const createUser = formData.get('create_user');
        const product = formData.get('buy_goodsProduct');
        const productNumber = formData.get('buy_goodsProduct_number');

        if (!orderId || !payMethod || !totalPrice || !createUser || !product || !productNumber) {
            Swal.fire('错误', '请填写所有必填字段', 'error');
            return;
        }

        // 验证订单ID格式和长度
        if (!/^[a-zA-Z0-9_-]+$/.test(orderId)) {
            Swal.fire('错误', '订单ID只能包含英文、数字、下划线和-', 'error');
            return;
        }
        if (orderId.length > 30) {
            Swal.fire('错误', '订单ID长度不能超过30个字符', 'error');
            return;
        }

        // 验证购买数量
        const selectedOption = document.getElementById('orderProduct').options[document.getElementById('orderProduct').selectedIndex];
        const stock = parseInt(selectedOption.getAttribute('data-stock'));
        if (parseInt(productNumber) > stock) {
            Swal.fire('错误', '购买数量不能超过商品库存', 'error');
            return;
        }

        // 立即关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('addOrderModal'));
        modal.hide();

        const loadingToast = Swal.fire({
            title: '添加中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.post('/api/order/create_order/', formData)
            .then(function(response) {
                if (response.data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: '订单添加成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        getOrderList();
                        form.reset();
                    });
                } else {
                    throw new Error(response.data.msg);
                }
            })
            .catch(function(error) {
                Swal.fire('错误', error.message || '添加订单失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 显示添加订单模态框
    function showAddOrderModal() {
        const modal = new bootstrap.Modal(document.getElementById('addOrderModal'));
        document.getElementById('addOrderForm').reset();
        // 自动生成一个订单ID
        generateOrderId();
                    modal.show();
    }

    // 删除订单
    function deleteOrder(orderId) {
        // 从表格行中获取订单ID
        const row = document.querySelector(`tr[data-id="${orderId}"]`);
        if (!row) {
            Swal.fire('错误', '找不到订单信息', 'error');
            return;
        }
        const orderIdValue = row.querySelector('td:first-child').textContent;

        Swal.fire({
            title: '确认删除',
            text: '确定要删除这个订单吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                axios.delete(`/api/order/delete_order/${orderIdValue}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: '订单删除成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                getOrderList();
                            });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '删除订单失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                    });
            }
        });
    }
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}